'use strict';

const {
	ESPIPE
} = require('constants');
const crypto = require('crypto');
const https = require('https');


module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/xnzf/queryBalance 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			openid,
			out_trade_no,
			env,
			user_id
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		
		
		// 查询用户openid  user_id
		let res1 = await vk.baseDao.selects({
			dbName: "uni-id-users",
			// 主表where条件
			whereJson: {
				_id: user_id
			},
		})
		
		let res2 = await vk.baseDao.selects({
			dbName: "vk-pay-config",
			// 主表where条件
			whereJson: {
				_id: res1.rows[0].pid
			},
		})
		
		let AppKey = res2.rows[0].wxpay["mp-weixin"].AppKey
		let OfferID = res2.rows[0].wxpay["mp-weixin"].OfferID
		let secret = res2.rows[0].wxpay["mp-weixin"].secret
		let appId = res2.rows[0].wxpay["mp-weixin"].appId

		let uri = "/xpay/query_order" // 查询余额

		let appkey = AppKey

		let sessionKey = res1.rows[0].sessionKey

		// 使用对象字面量的方式构造 post_body -----查询余额
		let post_body = JSON.stringify({
			openid: openid, // 用户openid
			env: 0, // 正式环境
			order_id: out_trade_no //订单号
		});

		// 调用方法
		try {
			let access_token = await getAccessToken();
			console.log("access_token", access_token);

			let paySig = calc_pay_sig(uri, post_body, appkey);

			let query_balance = await query_user_balance(access_token, paySig); // 查询余额

			return {
				code: 0,
				message: '请求成功',
				data: query_balance,
			};
		} catch (error) {
			console.log('请求失败', error);

			return {
				code: -1,
				message: '请求失败',
				error: error.message,
			};
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;

		// 支付签名
		function calc_pay_sig(uri, post_body, appkey) {
			const need_sign_msg = uri + '&' + post_body;
			const pay_sig = crypto.createHmac('sha256', appkey).update(need_sign_msg).digest('hex');
			return pay_sig;
		}



		// 获取 access_token
		async function getAccessToken() {
			const data = JSON.stringify({
				grant_type: 'client_credential',
				appid: appId,
				secret: secret,
			});
			const formUrl = 'https://api.weixin.qq.com/cgi-bin/stable_token';

			try {
				const response = await uniCloud.httpclient.request(formUrl, {
					method: 'POST',
					data: data,
				});
				const results = (response.data).toString('utf-8');
				// 字符串转换为对象
				const resultsStr = JSON.parse(results).access_token
				return resultsStr;
			} catch (error) {
				console.log('请求错误', error);
				throw error;
			}

		}

		// 查询余额
		async function query_user_balance(access_token, paySig) {

			const data = post_body
			const formUrl =
				`https://api.weixin.qq.com/xpay/query_order?access_token=${access_token}&pay_sig=${paySig}`;

			try {
				const response = await uniCloud.httpclient.request(formUrl, {
					method: 'POST',
					data: data,
				});
				console.log("response.data", response.data);
				const results = (response.data).toString('utf-8');
				console.log("余额信息", results);

				return results;
			} catch (error) {
				console.log('请求错误', error);
				throw error;
			}

		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}